import React from 'react';
import {browserHistory,Link} from 'react-router';
import { Form, Button, Input, Select, message,  Modal } from 'antd';
import config from '../../../config/config';
import $ from 'jquery';
const allRouter=config.router;
const FormItem = Form.Item;
const Option = Select.Option;
const token = sessionStorage.getItem('token');
class AddUserType extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            hasNamed:false,//验证重名
        }
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {
    }
    componentDidMount() {
        //判断是点击新增还是编辑跳转，如果是编辑，则请求数据显示在表单中
        //console.log(this.props.params.userTypeId);
        if(this.props.params.userTypeId != "0"){
            let url=allRouter.patientOrigin+'/grade/one/'+this.props.params.userTypeId;
            //console.log(url);
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data:{

                },
                success:data1=>{
                    if(data1.code===200){
                        let data=data1.gread;
                        //console.log(this.props.form.getFieldsValue());
                        this.props.form.setFieldsValue({
                            typeName:data.name,
                            treatment:data.treatment*100,
                            surgeryName:data.adjuvanttherapy*100,
                            chineseMedicine:data.chinesemedicine*100,
                            Medicine:data.westernmedicine*100,
                            registerFee:data.registered*100,
                            childrenMassage:data.infantiletuina*100,
                            acupuncture:data.acupuncture*100,
                            femaleCare:data.femininecare*100,
                            documentFee:data.costofrawmaterials*100,
                            otherFee:data.others*100,
                        });
                    }else{
                        console.log("获取会员类型信息出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        }
    }
    //保存会员类型
    saveData(){
        this.props.form.validateFields((err,values)=> {
            if(err){return}
            if(this.state.hasNamed){
                message.error('该会员类型名称已经存在!',1);
                return;
            }
            console.log(values);
            //发送Ajax请求，post
            let url=allRouter.patientOrigin+'/grade/save';
            //如果会员类型值为空，则return
            if(!values.typeName){
                return;
            }
         //console.log(postBody);
            //即是编辑状态
            if(this.props.params.userTypeId !== "0"){
                let url=allRouter.patientOrigin+'/grade/update';
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        name:values.typeName,
                        state:'启用',
                        treatment:values.treatment?values.treatment/100:1,
                        adjuvanttherapy:values.surgeryName?values.surgeryName/100:1,
                        chinesemedicine:values.chineseMedicine?values.chineseMedicine/100:1,
                        westernmedicine:values.Medicine?values.Medicine/100:1,
                        registered:values.registerFee?values.registerFee/100:1,
                        infantiletuina:values.childrenMassage?values.childrenMassage/100:1,
                        acupuncture:values.acupuncture?values.acupuncture/100:1,
                        femininecare:values.femaleCare?values.femaleCare/100:1,
                        costofrawmaterials:values.documentFee?values.documentFee/100:1,
                        others:values.otherFee?values.otherFee/100:1,
                        id:this.props.params.userTypeId
                    },
                    success:data=>{
                        if(data.code===200){
                            message.info('更改会员类型成功',);
                            browserHistory.push('/userTypeManage');
                        }else{
                            message.info('更改会员类型错误');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
                return;
            }
            //即是新增状态
            $.ajax({
                url:url,
                type: "POST",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data:{
                    name:values.typeName,
                    state:'启用',
                    treatment:values.treatment?values.treatment/100:1,
                    adjuvanttherapy:values.surgeryName?values.surgeryName/100:1,
                    chinesemedicine:values.chineseMedicine?values.chineseMedicine/100:1,
                    westernmedicine:values.Medicine?values.Medicine/100:1,
                    registered:values.registerFee?values.registerFee/100:1,
                    infantiletuina:values.childrenMassage?values.childrenMassage/100:1,
                    acupuncture:values.acupuncture?values.acupuncture/100:1,
                    femininecare:values.femaleCare?values.femaleCare/100:1,
                    costofrawmaterials:values.documentFee?values.documentFee/100:1,
                    others:values.otherFee?values.otherFee/100:1,
                },
                success:data=>{
                    console.log(data);
                    if(data.code===200){
                        message.info('增加成功',);
                        browserHistory.push('userTypeManage');
                    }else if(data.code===201){
                        message.error('患者来源名称已存在，请修改');
                    }else{
                        message.info('增加失败');
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回科室列表页面吗？',
            cancelText:'取消',
            okText:'确定',
            onCancel:()=>{
                //console.log('取消')
            },
            onOk:()=>{
                browserHistory.push('userTypeManage');
            }
        })
    }
    handleChange(e){
        let myRef=e.target.getAttribute('data');
        this.refs[myRef].innerHTML=(e.target.value/10).toFixed(1)+"折";
    }
    //验证名称是否重复
    hadnamed(e){
        console.log(e.target.value);
        let scheduleName = e.target.value;
        let url=allRouter.patientOrigin+'/grade/hadnamed';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                name:e.target.value
            },
            success:data => {
                console.log(data);
                if(data.code===201){
                    this.props.form.setFields({
                        typeName: { value: scheduleName,errors: [new Error(data.mes)] }
                    });
                    this.setState({
                        hasNamed:true,
                    })
                }else{
                    this.setState({
                        hasNamed:false,
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    render() {
        const formItemLayout = { labelCol: { span: 3 }, wrapperCol: { span: 18 } };
        const { getFieldDecorator } = this.props.form;
        return (
            <div className='container'>
                <div className='add-department-box'>
                    <div className="show-template">
                        <span>*{this.props.params.userTypeId != "0"?"编辑":"新增"}会员类型</span>
                    </div>
                    <Form>
                        <div className='storeRow' >
                            <FormItem {...{ labelCol: { span: 3 }, wrapperCol: { span: 18 } }} label="类型名称" style={{ display: 'inline-block', width: '90%' }} >
                                <div style={{display:'flex'}}>
                                    {getFieldDecorator('typeName', {
                                        rules: [{ required: true, message: '会员类型名称不能为空' }],
                                    })(
                                        <Input placeholder="请输入中文名称" onKeyUp={this.hadnamed.bind(this)}/>
                                    )}
                                </div>
                            </FormItem>
                        </div>
                        <div>
                            <p style={{fontSize:'20px',margin:'0'}}>折扣设置<span style={{fontSize:'12px'}}>（0-100之间的整数，50%表示5折；5%表示0.5折</span></p>
                            <hr/>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='治疗' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('treatment', {
                                    rules: [{pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                    <Input data='b' onChange={this.handleChange.bind(this)} placeholder="请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="b">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='外科治疗' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                    {getFieldDecorator('surgeryName', {
                                        rules: [{  pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                    })(
                                            <Input placeholder=" 请输入0-100之间的整数" data='a' addonAfter="%"  style={{ display: 'inline-block', width: '90%' }} onChange={this.handleChange.bind(this)}/>
                                    )}
                                    <span ref="a">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='中药' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('chineseMedicine', {
                                    rules: [{ pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='c' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="c">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='西药' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('Medicine', {
                                    rules: [{  pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='d' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="d">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='挂号' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('registerFee', {
                                    rules: [{ pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='e' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="e">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='小儿推拿' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('childrenMassage', {
                                    rules: [{  pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='f' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="f">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='针灸/拔罐/按摩' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('acupuncture', {
                                    rules: [{ pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='g' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="g">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='女性护理' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('femaleCare', {
                                    rules: [{ pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='h' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="h">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='材料费' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('documentFee', {
                                    rules: [{ pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='i' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="i">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                        <div className='storeRow'>
                            <FormItem {...formItemLayout} label='其它收费' style={{ display: 'inline-block', width: '100%' }} >
                                <div style={{display:'flex'}}>
                                {getFieldDecorator('otherFee', {
                                    rules: [{ pattern:/^(0?\d?\d|100)$/,message: '请输入0-100之间的整数' }],
                                })(
                                        <Input data='j' onChange={this.handleChange.bind(this)} placeholder=" 请输入0-100之间的整数" addonAfter="%"  style={{ display: 'inline-block', width: '90%' }}/>
                                )}
                                    <span ref="j">0.0折</span>
                                </div>
                            </FormItem>
                        </div>
                    </Form>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>
                </div>
            </div>
        )
    }
}
const AddUserTypeForm = Form.create()(AddUserType);
export default AddUserTypeForm;